package com.yeskery.nut.application;

import com.yeskery.nut.core.*;
import com.yeskery.nut.http.BaseRequest;
import com.yeskery.nut.http.FormDataRequest;
import com.yeskery.nut.http.UrlEncodedRequest;
import com.yeskery.nut.util.StringUtils;

/**
 * Nut Server 处理接口
 * @author sprout
 * @version 1.0
 * 2022-08-11 14:46
 */
public interface NutServerProcess {

    /**
     * Nut Server 进行的数据处理方法，该方法主要实现了请求转发，
     * 请求响应等 HTTP 全过程响应方法
     * @param request 请求对象
     * @param response 响应对象
     * @param dispatcher 请求转发器
     * @param sessionManager session 管理器
     */
    default void process(Request request, Response response, Dispatcher dispatcher, SessionManager sessionManager) {
        if (request.isEmpty()) {
            return;
        }
        //转换对应的Request对象
        if (request.getMethod() != Method.GET && request.getBody() != null && request.getBody().length > 1) {
            String contentType = request.getHeader(HttpHeader.CONTENT_TYPE);
            if (!StringUtils.isEmpty(contentType)) {
                if (MediaType.APPLICATION_X_WWW_FORM_URLENCODED.getValue().equalsIgnoreCase(contentType)) {
                    request = new UrlEncodedRequest((BaseRequest) request);
                } else if (contentType.toLowerCase().startsWith(MediaType.APPLICATION_FORM_DATA.getValue())) {
                    request = new FormDataRequest((BaseRequest) request);
                }
            }
        }
        //初始化Session环境
        sessionManager.initSessionEnv(request, response);
        //分发请求
        try {
            dispatcher.dispatch(request, response);
        } catch (Exception e) {
            throw new NutException("The Dispatcher[" + dispatcher.getClass().getName() + "] Handle Fail.", e);
        }
    }
}
